﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Ruandao.MiniFace
{
    public class PagerWidget : WidgetBase
    {
        #region Property

        string formId;          // form元素的id属性值。
        string urlFormat;       // 请求地址，包含{0}用来传递页码参数
        string pageName;        // 传递页码的隐藏域的name属性值。
        int pageSize;           // 每页显示10条
        int pageNum;            // 显示的页码数量
        int curPage;            // 当前页码, 页码从1开始，不是从0开始计数。

        int totalSize;          // 总记录数

        int totalPage = 0;      // 总的页码数量。

        // key表示页码，value表示显示的页码字符。
        List<KeyValuePair<int, string>> pageList = new List<KeyValuePair<int, string>>();

        #endregion

        public PagerWidget()
        {
            this.formId = "form1"; 
            this.urlFormat = "/?pageCode={0}";
            this.pageName = "pageCode";
            this.pageSize = 10;
            this.pageNum = 5;
            this.curPage = 1;
        }
        
        private void DataBind()
        {
            if (Properties.ContainsKey("CurPage"))
            {
                int result =1 ;
                int.TryParse(Properties["CurPage"], out result);
                this.curPage = result;
            }
            if ( Properties.ContainsKey("TotalSize") )  this.totalSize = int.Parse(Properties["TotalSize"]);
            if ( Properties.ContainsKey("PageSize") )  this.pageSize = int.Parse(Properties["PageSize"]);
            if ( Properties.ContainsKey("PageName"))    this.pageName = Properties["PageName"];
            if ( Properties.ContainsKey("UrlFormat") )  this.urlFormat = Properties["UrlFormat"];
            if ( Properties.ContainsKey("FormId") )     this.formId = Properties["FormId"];

            // 获取totalPage
            this.totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize) : (totalSize / pageSize) + 1;
            // 获取pageList
            int leftPageNum = (curPage - pageNum < 1) ? 1 : (curPage - pageNum);//左边界
            int rightPageNum = (curPage + pageNum > totalPage) ? totalPage : (curPage + pageNum);//右边界
            int pageCount = rightPageNum - leftPageNum + 1;
            var sourceList = Enumerable.Range(leftPageNum, pageCount);
            pageList.AddRange(sourceList.Select(
                    p => new KeyValuePair<int, string>(p, p.ToString())
                ));

        }

        public override void Render(TemplateContext templateContext, System.IO.TextWriter writer)
        {
            DataBind();

            dynamic widgetArgs = new System.Dynamic.ExpandoObject();
            widgetArgs.FormId = this.formId;
            widgetArgs.UrlFormat = this.urlFormat;
            widgetArgs.PageName = this.pageName;
            widgetArgs.PageSize = this.pageSize;
            widgetArgs.PageNum = this.pageNum;
            widgetArgs.CurPage = this.curPage;
            widgetArgs.TotalSize = this.totalSize;
            widgetArgs.TotalPage = this.totalPage;
            templateContext.PythonScope.SetVariable("WidgetArgs", widgetArgs);

            foreach (var content in this.WidgetTemplate.Contents)
            {
                var template = content as TemplateItem;
                if (template == null)
                {
                    content.Render(templateContext, writer);
                    continue;
                }
                if (pageList.Count == 0) continue;

                int startPage = pageList[0].Key;//开始页
                int endPage = pageList[pageList.Count - 1].Key;//结束页

                // 渲染子模板。
                switch (template.ItemName)
                {
                    case "PrevTemplate":
                        if ( curPage == startPage ) break;
                        string prevUrl = string.Format(this.urlFormat, curPage-1);
                        string prevHref = string.Format("javascript:$('#{0} #{1}').attr('value',{2});$('#{0}').submit();", this.formId, this.pageName, curPage - 1);
                        templateContext.PythonScope.SetVariable("PrevUrl", prevUrl);
                        templateContext.PythonScope.SetVariable("PrevHref", prevHref);
                        foreach (var sub in this.WidgetTemplate.TemplateItems["PrevTemplate"])
                        {
                            sub.Render(templateContext, writer);
                        }
                        templateContext.PythonScope.RemoveVariable("PrevUrl");
                        templateContext.PythonScope.RemoveVariable("PrevHref");
                        break;

                    case "NextTemplate":
                        if ( curPage == endPage ) break;
                        string nextUrl = string.Format(this.urlFormat, curPage+1);
                        string nextHref = string.Format("javascript:$('#{0} #{1}').attr('value',{2});$('#{0}').submit();", this.formId, this.pageName, this.curPage + 1);
                        templateContext.PythonScope.SetVariable("NextUrl", nextUrl);
                        templateContext.PythonScope.SetVariable("NextHref", nextHref);
                        foreach (var sub in this.WidgetTemplate.TemplateItems["NextTemplate"])
                        {
                            sub.Render(templateContext, writer);
                        }
                        templateContext.PythonScope.RemoveVariable("NextUrl");
                        templateContext.PythonScope.RemoveVariable("NextHref");
                        break;

                    case "ItemTemplate":
                        foreach (var item in pageList)
                        {
                            templateContext.PythonScope.SetVariable("Item", item);
                            string itemUrl = string.Format(this.urlFormat, item.Key);
                            string itemHref = string.Format("javascript:$('#{0} #{1}').attr('value',{2});$('#{0}').submit();", this.formId, this.pageName, item.Key);
                            templateContext.PythonScope.SetVariable("ItemUrl", itemUrl);
                            templateContext.PythonScope.SetVariable("ItemHref", itemHref);
                            if (item.Key == this.curPage)
                            {
                                foreach (var sub in this.WidgetTemplate.TemplateItems["CurrentItemTemplate"])
                                {
                                    sub.Render(templateContext, writer);
                                }
                            }
                            else
                            {
                                foreach (var sub in this.WidgetTemplate.TemplateItems["ItemTemplate"])
                                {
                                    sub.Render(templateContext, writer);
                                }
                            }
                            templateContext.PythonScope.RemoveVariable("Item");
                            templateContext.PythonScope.RemoveVariable("ItemUrl");
                            templateContext.PythonScope.RemoveVariable("ItemHref");
                        } // end of foreach page list

                        break;

                    default:
                        throw new Exception("在ContentListWidget中不支持子模板：" + template.ItemName + "。");
                }
            } // end of foreach widget contents

            templateContext.PythonScope.RemoveVariable("WidgetArgs");
        }

    }
}
